import {
  AuthLoginRequest,
  AuthLoginResponse,
  AuthRegisterRequest,
  AuthRegisterResponse,
} from "@/types/api";
import { BcryptService } from "../vendor/bcrypt";
import { JsonwebtokenService } from "../vendor/jsonwebtoken";
import prisma from "@/db/prisma";
import { ServiceException } from "@/error/exception";
import { rootValidator } from "@/utils/validator";

export class AuthService {
  constructor(
    private bcryptService: BcryptService,
    private jsonwebtokenService: JsonwebtokenService
  ) {}

  async login(dto: AuthLoginRequest): Promise<AuthLoginResponse> {
    return prisma.$transaction(async (prisma) => {
      const user = await prisma.user.findFirst({
        where: { username: dto.username, deletedAt: null },
        include: {
          avatar: true,
        },
      });
      if (!user) {
        throw new ServiceException("用户名不存在", 4);
      }
      const compare = await this.bcryptService.compare(
        dto.password,
        user.password
      );
      if (!compare) {
        throw new ServiceException("密码错误", 4);
      }
      const payload = {
        userId: user.id,
        isRoot: rootValidator(user.username),
      };
      const token = this.jsonwebtokenService.sign(payload);
      const { password, avatarId, ...userRest } = user;
      return {
        token,
        user: userRest,
      };
    });
  }

  async register(dto: AuthRegisterRequest): Promise<AuthRegisterResponse> {
    return prisma.$transaction(async (prisma) => {
      const user = await prisma.user.findFirst({
        where: { username: dto.username, deletedAt: null },
      });

      if (user) {
        throw new ServiceException("用户名已存在", 4);
      }
      const password = await this.bcryptService.hash(dto.password);
      await prisma.user.create({
        data: {
          username: dto.username,
          password,
          email: dto.email || "",
        },
      });
      return true;
    });
  }
}
